package com.ydzt.fanka.server.space.bufferreceiver;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;

import com.ydzt.fanka.server.domain.BufferRecord;
import com.ydzt.fanka.server.init.InitData;
import com.ydzt.fanka.server.init.SynchronizedVariable;
import com.ydzt.fanka.server.utils.FileUtil;

/*
 * 将buffer文件夹中的报文放入消息处理队列
 * */
public class BufferReceiverServer extends Thread {
	static Logger logger = Logger.getLogger(BufferReceiverPool.class.getName());
	BufferRecord record_1 = null;

	String nodeID = "00000000";
	public void run() {

		if (InitData.nodeType.equals("00")) {
			List<String> DrCollectionArray = new ArrayList<String>();
			HashMap<String,String> map = InitData.getInstance().getSupplierMap();
			if(map != null){
				Iterator<String> iter = map.keySet().iterator();
				while(iter.hasNext()){
					nodeID = iter.next();
					if(!"00000000".equals(nodeID)){
						logger.info("BufferReceiverServer取得食堂节点:" + nodeID);
						DrCollectionArray.add(nodeID);
					}
				}
			}
			else{
				logger.info("未取到食堂map");
			}
			
			try {
				if (DrCollectionArray != null) {
					int iDrConut = DrCollectionArray.size();
					if (iDrConut != 0) {
						while (true) {
							for (int i = 0; i < iDrConut; i++) {
								record_1 = FileUtil
										.getBufferFile(DrCollectionArray.get(i));
								if (record_1 != null) {
									// 入队列
									BufferReceiverPool.getInstants()
											.addSocketProducer(record_1);
								} else {
									continue;
								}
							}
						}
					} else {
						logger.info("获取到0个食堂的IP");
					}
				}
			} catch (Exception e) {
				logger.error(e);
				logger.info(e);
			}
		} else {
			try {
				while (true) {
					if(!SynchronizedVariable.getInstance().isBuffLock()){
						record_1 = FileUtil.getBufferFile();
						if (record_1 != null) {
							// 入队列
							BufferReceiverPool.getInstants().addSocketProducer(
									record_1);
						} else {
							continue;
						}
					}
					else{
						logger.info("当前食堂正在进行日终");
						try {
							for(int i = 10;i > 0;i --){
								Thread.sleep(1000);
								logger.info("等待日终操作结束  -------" + i + "秒");
							}
						} catch (InterruptedException e) {
							continue;
						}
					}
				}

			} catch (Exception e) {
				logger.error(e);
				logger.info(e);
			}

		}

	}
}